<template>
	<view>
		<!-- 加载提示 -->
		<loading v-if="loading"></loading>
		<!-- 顶部标题栏 -->
		<top-bar></top-bar>

		<!-- 阅读内容 -->
		<mescroll-uni ref="mescrollRef" @init="mescrollInit" :down="downOption" :up="upOption" @down="downCallback" @up="upCallback"
		 @scroll="onScroll" style="overflow-anchor: none;">
			<view @click="handleToMenu" class="read-content">
				<view class="read-box" :class="`chapater-${item.index}`" :style="{'background': readTheme.defaultBackground,'font-size':readSetting.fontSize * 2 + 'rpx','font-family':readSetting.fontFamily,'padding-right':readSetting.pagePadding + 'rpx','padding-left':readSetting.pagePadding + 'rpx','padding-top': (iStatusBarHeight < 30 ? 0 : iStatusBarHeight) + 60 + 'px'}"
				 v-for="(item,index) in contentList" :key="index" :data-title="item.title" :data-index="item.index" style="overflow: hidden;">
					<text class="read-title" :style="{'font-size':readSetting.fontSize*3.2+'rpx'}">{{item.title}}</text>
					<u-parse :html="sectionDistanceFilter(item.content)" :style="{'line-height':readSetting.lineDistance + 'rpx'}"></u-parse>
				</view>
			</view>
		</mescroll-uni>

		<!-- 导航栏 -->
		<nav-bar :navBarShow="navBarShow" :bookName="bookName" :isInShelf='isInShelf' @handleAddBookShelf="handleAddBookShelf"></nav-bar>

		<!-- 标题栏 -->
		<bottom-bar :chapterTitle="chapterTitle" :chapterIndex="chapterIndex" :bookId="bookId"></bottom-bar>


		<!-- 设置面板 -->
		<u-popup v-model="navBarShow" mode="bottom" :mask="false" z-index="1001">
			<view class="read-menu">
				<u-grid :col="4" :border="false" hover-class="none">
					<u-grid-item :style="{'background': readTheme.mainBackground}" @click="handleToChapterList">
						<u-icon name="../../static/image/list.png" :size="46"></u-icon>
						<view class="grid-text">章节</view>
					</u-grid-item>
					<u-grid-item :style="{'background': readTheme.mainBackground}" @click="handleToBrightness">
						<u-icon name="../../static/image/screen.png" :size="46"></u-icon>
						<view class="grid-text">亮度</view>
					</u-grid-item>
					<u-grid-item :style="{'background': readTheme.mainBackground}" @click="handleToChangeTheme">
						<u-icon :name="'../../static/image/'+readTheme.icon+'.png'" :size="46"></u-icon>
						<view class="grid-text">{{readTheme.item}}</view>
					</u-grid-item>
					<u-grid-item :style="{'background': readTheme.mainBackground}" @click="handleToSetting">
						<u-icon name="../../static/image/setting.png" :size="46"></u-icon>
						<view class="grid-text">设置</view>
					</u-grid-item>
				</u-grid>
			</view>
		</u-popup>

		<!-- 亮度设置 -->
		<u-popup v-model="brightness" mode="bottom" :mask="false">
			<view class="screen-box" :style="{'background': readTheme.tabBackground}">
				<u-icon name="minus-circle" size="40" @click="handleToMinuBrightness"></u-icon>
				<view style="width:70vw;display:inline-block;padding: 0 8rpx;">
					<u-slider v-model="brightnessValue" height="10" block-width="40" :active-color="readTheme.background"></u-slider>
				</view>
				<u-icon name="plus-circle" size="40" @click="handleToPlusBrightness"></u-icon>
			</view>
		</u-popup>

		<!-- 其他设置 -->
		<setting-menu ref="settingMenu"></setting-menu>

		<!-- 章节列表 -->
		<chapter-list ref="chapterList" :bookName="bookName" :bookId="bookId" :index="chapterIndex"></chapter-list>

		<!-- 提示 -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import {
		getRead
	} from "@/api/read.js"
	import {
		getAllChapterList
	} from '@/api/chapter.js'
	import _ from 'lodash'
	import topBar from './components/topBar/topBar.vue'
	import bottomBar from './components/bottomBar/bottomBar.vue'
	import navBar from './components/navBar/navBar.vue'
	import chapterList from './components/chapterList/chapterList.vue'
	import settingMenu from './components/settingMenu/settingMenu.vue'
	import loading from './components/loading/loading.vue'
	import {
		mapState,
		mapGetters
	} from 'vuex'
	import {
		updateBookShelfList
	} from '@/api/shelf.js'
	export default {
		components: {
			topBar,
			bottomBar,
			navBar,
			chapterList,
			settingMenu,
			loading
		},
		mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
		data() {
			return {
				contentList: [],
				bookId: 0,
				chapterId: 0,
				chapterIndex: 0,
				chapterTitle: '',
				bookName: '',
				navBarShow: false,
				pageSize: 50,
				brightnessValue: 0,
				brightness: false,
				isInit: false,
				loading: true,
				observer: null,
				height: 0
			}
		},
		computed: {
			...mapState({
				token: state => state.global.token,
				iStatusBarHeight: state => state.global.iStatusBarHeight,
				windowHeight: state => state.global.windowHeight,
				shelfList: state => state.shelf.shelfList,
				readSetting: state => state.setting.readSetting
			}),
			...mapGetters({
				readTheme: 'readTheme'
			}),
			isInShelf() {
				return this.shelfList.some(item => {
					return item.book_id == this.bookId
				})
			},
			upOption() {
				return {
					bgColor: this.readTheme.background,
					textColor: this.readTheme.color,
					offset: 2000,
					textNoMore: '人家是有底线的~',
					onScroll: true,
					toTop: {
						src: ''
					}
				}
			},
			downOption() {
				return {
					auto: false,
					bgColor: this.readTheme.defaultBackground,
					textColor: this.readTheme.defaultColor
				}
			},
			nextChapterId() {
				return this.contentList.length > 0 ? this.contentList[this.contentList.length - 1].next_chapter_id : this.chapterId
			},
			lastChapterId() {
				return this.contentList.length > 0 ? this.contentList[0].last_chapter_id : this.chapterId
			}
		},
		watch: {
			// #ifdef APP-PLUS
			brightnessValue(val) {
				uni.setScreenBrightness({
					value: val / 100,
					success: function() {
						console.log('success');
					}
				});
			},
			// #endif
			chapterIndex(val) {
				const chapterId = this.contentList.find(item => {
					return item.index == val
				}).chapter_id
				// 更新书架
				this.updateBookShelf(chapterId, val)
				// 设置最后阅读的书籍
				this.$store.commit('SET_LAST_READ_BOOK_INFO', {
					bookId: this.bookId,
					chapterId
				})
				// 更新阅读记录
				this.$store.dispatch('updateHistoryReadList', {
					bookId: this.bookId,
					lastReadChapterId: chapterId,
					lastReadChapterName: this.chapterTitle,
				})
			},
			readTheme(theme) {
				this.mescroll.optDown.bgColor = theme.defaultBackground
				this.mescroll.optDown.textColor = theme.defaultColor
				this.mescroll.optUp.bgColor = theme.defaultBackground
				this.mescroll.optDown.textColor = theme.defaultColor
			}
		},
		onLoad(option) {
			this.bookId = option.bookId
			this.chapterId = option.chapterId
			// #ifdef APP-PLUS
			if (this.readSetting.lightForever) {
				uni.setKeepScreenOn({
					keepScreenOn: true
				});
			}
			// #endif
			if (this.token) {
				this.$store.dispatch('updateShelfList')
			}
			this.$store.dispatch('getReadBookInfo', this.bookId)
		},
		onReady() {
			this.observer = uni.createIntersectionObserver(this, {
				observeAll: true
			})
		},
		onShow() {
			// #ifdef APP-PLUS
			this.getScreenBrightness()
			// #endif
		},
		onBackPress(event) {
			const pages = getCurrentPages()
			if (pages.length === 1) {
				uni.switchTab({
					url: '/pages/home/index'
				})
				return true;
			}
		},
		onUnload() {
			// #ifdef APP-PLUS
			uni.setKeepScreenOn({
				keepScreenOn: false
			});
			// #endif
		},
		methods: {
			/*下拉刷新的回调 */
			downCallback() {
				if (this.lastChapterId == 0) { // 到顶了
					this.$refs.uToast.show({
						title: '已经是第一章了',
						type: 'warning'
					})
					this.mescroll.endSuccess();
					return
				}
				getRead({
					bookId: this.bookId,
					chapterId: this.lastChapterId
				}).then(async res => {
					this.mescroll.endSuccess();
					res.data.content = await this.getContent(res.data.path)
					this.contentList.unshift(res.data);
				}).catch(() => {
					this.mescroll.endErr();
				})
			},
			/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
			upCallback() {
				if (!this.isInit) {
					this.loading = true
				}
				if (this.nextChapterId == 0) { // 到底了
					this.$refs.uToast.show({
						title: '已经是最后一章了',
						type: 'warning'
					})
					this.mescroll.endSuccess(0, false);
					return
				}
				getRead({
					bookId: this.bookId,
					chapterId: this.nextChapterId
				}).then(async res => {
					this.mescroll.endSuccess(10, Boolean(res.data.index));
					res.data.content = await this.getContent(res.data.path)
					this.contentList = this.contentList.concat(res.data);
					if (!this.bookName) this.bookName = res.data.name
					if (!this.chapterTitle) this.chapterTitle = res.data.title
					if (!this.chapterIndex) this.chapterIndex = res.data.index
					if (!this.isInit) {
						this.isInit = true
						this.loading = false
					}
				}).catch(() => {
					this.mescroll.endErr();
				})
			},
			// 获取小说内容
			getContent(url){
				return new Promise((resolve, reject) =>{
					uni.request({
					    url,
					    success: (res) => resolve(res.data.replace(/#{3}.*?#{3}/g,'')),
						fail: e => reject(e)
					});
				})
			},
			// 监听滚动
			onScroll(mescroll) {
				this.scrollView()
				this.checkContent()
			},
			scrollView: _.throttle(function(e) {
				if (!this.observer) return
				this.observer.observe('.read-box', async (res) => {
					if (res && res.intersectionRatio !== 0) {
						if (this.chapterTitle == res.dataset.title && this.chapterIndex == res.dataset.index) return
						if (this.chapterTitle !== res.dataset.title && res.boundingClientRect.top > 0) return
						this.chapterTitle = res.dataset.title
						this.chapterIndex = res.dataset.index
					}
				})
			}, 200, {
				'trailing': false
			}),
			checkContent: _.debounce(function() {
				if (this.contentList.length > 10) { // 章节内容超过5章 重置下
					if (this.chapterIndex == this.contentList[this.contentList.length - 1].index) {
						this.loading = true
						this.$u.getRect(`.chapater-${this.chapterIndex}`).then(rect => {
							const scrollTop = Math.abs(rect.top)
							while (this.contentList.length > 1) {
								this.contentList.shift()
							}
							this.mescroll.scrollTo(scrollTop, 0)
							setTimeout(() =>{
								this.loading = false
							},500)
						})
					}
				}
			}, 200),
			// 打开菜单
			handleToMenu: _.throttle(function(e) {
				let offsetY = this.windowHeight / 3;
				let currentY = e.target.y;
				if (currentY <= offsetY) {

				} else if (offsetY <= currentY && currentY <= offsetY * 2) {
					this.navBarShow = !this.navBarShow;
				} else if (currentY >= offsetY * 2 && currentY <= this.windowHeight) {

				}
			}, 200, {
				'trailing': false
			}),
			// 设置段落距离
			sectionDistanceFilter(content) {
				let _content = content;
				if (/<br><br>/.test(_content)) {
					switch (this.readSetting.sectionDistance) {
						case '0':
							_content = _content.replace(/<br><br>/g, '')
							_content = _content.replace(/<br>    /g, '    ')
							break;
						case '1':
							_content = _content.replace(/<br><br>/g, '')
							break;
						case '2':
							break;
						default:
							break;
					}
				} else {
					switch (this.readSetting.sectionDistance) {
						case '0':
							_content = _content.replace(/<br>    /g, '')
							break;
						case '1':
							_content = _content.replace(/<br>     /g, '<br><br>')

							break;
						case '2':
							_content = _content.replace(/<br>     /g, '<br><br><br><br>')
							break;
						default:
							break;
					}
				}
				return _content
			},
			// 切换主题
			handleToChangeTheme: _.throttle(function(e) {
				this.$store.commit('SET_READ_SETTING', {
					key: 'isDarkMode',
					value: !this.readSetting.isDarkMode
				})
			}, 200, {
				'trailing': false
			}),
			// 获取屏幕亮度
			getScreenBrightness() {
				uni.getScreenBrightness({
					success: (res) => {
						this.brightnessValue = (res.value * 100).toFixed(0);
					}
				});
			},
			// 亮度设置
			handleToBrightness() {
				this.navBarShow = !this.navBarShow;
				this.brightness = !this.brightness;
			},
			// 减少亮度
			handleToMinuBrightness() {
				if (this.brightnessValue < 10) {
					this.brightnessValue = 0
				} else {
					this.brightnessValue = this.brightnessValue - 10
				}
			},
			// 增加亮度
			handleToPlusBrightness() {
				if (this.brightnessValue > 90) {
					this.brightnessValue = 100
				} else {
					this.brightnessValue = this.brightnessValue + 10
				}
			},
			// 打开章节列表面板
			handleToChapterList() {
				this.navBarShow = !this.navBarShow;
				this.$refs.chapterList.show = !this.$refs.chapterList.show
			},
			// 加入or撤出书架
			handleAddBookShelf: _.debounce(async function() {
				if (!this.token) {
					this.$refs.uToast.show({
						title: '您还未登录',
						type: 'error',
						position: 'top'
					})
					return;
				}
				let title = ''
				if (this.isInShelf) {
					const bookShelfId = this.shelfList.find(item => {
						return item.book_id == this.bookId
					}).book_shelf_id
					await this.$store.dispatch('delBookFromShelf', bookShelfId)
					title = '成功撤出书架'
				} else {
					await this.$store.dispatch('addBookToShelf', {
						bookId: this.bookId,
						lastReadChapter: this.lastReadChapterId === 0 ? this.chapterList[0].id : this.lastReadChapterId,
						index: this.lastReadChapterIndex ? this.lastReadChapterIndex : 0
					})
					title = '成功加入书架'
				}
				await this.$store.dispatch('updateShelfList')
				this.$refs.uToast.show({
					title,
					type: 'success',
					position: 'top'
				})
			}, 500, {
				'leading': true,
				'trailing': false
			}),
			// 更新书架信息
			updateBookShelf(lastReadChapter, index) {
				if (this.token) {
					updateBookShelfList({
						Authorization: 'Bearer ' + this.token
					}, {
						bookId: this.bookId,
						lastReadChapter,
						index
					})
				}
			},
			// 设置
			handleToSetting() {
				this.navBarShow = !this.navBarShow;
				this.$refs.settingMenu.show = !this.$refs.settingMenu.show;
			}
		}
	}
</script>

<style scoped>
	.read-load {
		position: fixed;
		top: 0;
		left: 0;
		height: 100vh;
		width: 100vw;
		z-index: 10001;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.read-box {
		min-height: 3000rpx;
		scroll-behavior: smooth;
	}
	
	.read-title{
		display: inline-block;
		margin-bottom: 30upx;
	}

	.slider-box {
		position: fixed;
		bottom: 150px;
		left: 10vw;
		width: 80vw;
		padding: 10px 5vw;
		border-radius: 4px;
	}

	.chapter-slider {
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 8vw;
	}

	.screen-box {
		height: 160rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 4vw;
	}


	.font-family {
		border: 2rpx solid #000000;
		border-radius: 40rpx;
		padding: 6rpx 20rpx;
		margin-right: 10rpx;
	}

	.active {
		border-color: #2B85E4;
		color: #2B85E4;
	}

	.current-chapter {
		color: rgb(146, 200, 255);
	}

	.status-bar {
		height: var(--status-bar-height);
		width: 100%;
	}

	.scroll-wrapper {
		position: fixed;
		top: 0;
		left: 0;
		height: 100vh;
		width: 100vw;
		background-color: transparent;
		z-index: 1000;
		touch-action: none;
	}

	.badge-button {
		padding: 4rpx 6rpx;
		background-color: #2B85E4;
		color: #fff;
		border-radius: 10rpx;
		font-size: 30rpx;
		line-height: 1;
	}
</style>
